<!-- 组织机构 组件 -->
<template>
  <a-scrollbar class="org-tree" style="max-height: calc(100vh - 165px); overflow: auto">
    <div class="org-tlt">组织机构 </div>
    <div class="org-buttons">
      <div class="org-i" v-permission="'svms:merchant:organization.editlist'">
        <div
          @click="() => orgEdit(chooseOrgData && !chooseOrgData.top, chooseOrgData)"
          :class="[
            'org-button',
            chooseOrgData && !chooseOrgData.top ? (editMouseIn == true ? 'org-mouse-active' : 'org-button-active') : '',
          ]"
          @mouseenter="
            () => {
              editMouseIn = true
            }
          "
          @mouseleave="
            () => {
              editMouseIn = false
            }
          "
        >
          <SvgIcon
            name="edit-org"
            class="org-icon"
            :color="chooseOrgData && !chooseOrgData.top ? (editMouseIn == true ? '#165DFF' : '#4E5969') : '#C9CDD4'"
          />
          <span>编辑</span>
          <div class="org-line"></div>
        </div>
      </div>
      <div class="org-i" v-permission="'svms:merchant:organization.addlist'">
        <div
          @click="() => orgAdd(chooseOrgData, chooseOrgData)"
          :class="['org-button', chooseOrgData ? (addMouseIn == true ? 'org-mouse-active' : 'org-button-active') : '']"
          @mouseenter="
            () => {
              addMouseIn = true
            }
          "
          @mouseleave="
            () => {
              addMouseIn = false
            }
          "
        >
          <SvgIcon name="add-org" class="org-icon" :color="chooseOrgData ? (addMouseIn == true ? '#165DFF' : '#4E5969') : '#C9CDD4'" />
          <span>新增</span>
          <div class="org-line"></div>
        </div>
      </div>
      <div class="org-i" v-permission="'svms:merchant:organization.deletelist'">
        <div
          @click="() => orgDelete(chooseOrgData && !chooseOrgData.top && chooseOrgData.canDelete, chooseOrgData)"
          :class="[
            'org-button',
            chooseOrgData && !chooseOrgData.top && chooseOrgData.canDelete
              ? deleteMouseIn == true
                ? 'org-mouse-active'
                : 'org-button-active'
              : '',
          ]"
          @mouseenter="
            () => {
              deleteMouseIn = true
            }
          "
          @mouseleave="
            () => {
              deleteMouseIn = false
            }
          "
        >
          <SvgIcon
            name="delete-org"
            class="org-icon"
            :color="
              chooseOrgData && !chooseOrgData.top && chooseOrgData.canDelete ? (deleteMouseIn == true ? '#165DFF' : '#4E5969') : '#C9CDD4'
            "
          />
          <span>删除</span>
          <div class="org-line"></div>
        </div>
      </div>
      <div class="org-i" v-permission="'svms:merchant:organization.uplist'">
        <div
          @click="() => orgUp(chooseOrgData && !chooseOrgData.top && chooseOrgData.sort != 1, chooseOrgData)"
          :class="[
            'org-button',
            chooseOrgData && !chooseOrgData.top && chooseOrgData.sort != 1
              ? upMouseIn == true
                ? 'org-mouse-active'
                : 'org-button-active'
              : '',
          ]"
          @mouseenter="
            () => {
              upMouseIn = true
            }
          "
          @mouseleave="
            () => {
              upMouseIn = false
            }
          "
        >
          <SvgIcon
            name="up-org"
            class="org-icon"
            :color="
              chooseOrgData && !chooseOrgData.top && chooseOrgData.sort != 1 ? (upMouseIn == true ? '#165DFF' : '#4E5969') : '#C9CDD4'
            "
          />
          <span>上移</span>
          <div class="org-line"></div>
        </div>
      </div>
      <div class="org-i" v-permission="'svms:merchant:organization.downlist'">
        <div
          @click="() => orgDown(chooseOrgData && !chooseOrgData.top && chooseOrgData.last != 1, chooseOrgData)"
          :class="[
            'org-button',
            chooseOrgData && !chooseOrgData.top && chooseOrgData.last != 1
              ? downMouseIn == true
                ? 'org-mouse-active'
                : 'org-button-active'
              : '',
          ]"
          @mouseenter="
            () => {
              downMouseIn = true
            }
          "
          @mouseleave="
            () => {
              downMouseIn = false
            }
          "
        >
          <SvgIcon
            name="down-org"
            class="org-icon"
            :color="
              chooseOrgData && !chooseOrgData.top && chooseOrgData.last != 1 ? (downMouseIn == true ? '#165DFF' : '#4E5969') : '#C9CDD4'
            "
          />
          <span>下移</span>
        </div>
      </div>
    </div>
    <a-tree v-if="treeData.length > 0" blockNode :checkable="false" :data="treeData" show-line @select="getSelectedNodes">
      <template #switcher-icon="node, { isLeaf }">
        <icon-caret-down v-if="!isLeaf" />
        <template v-if="isLeaf">
          <icon-user-group v-if="node.orgType == 2" />
          <icon-home v-else />
        </template>
      </template>
    </a-tree>
  </a-scrollbar>
  <!-- 添加机构 -->
  <organization-form ref="organizationEdit" @reset="orgOperate" />
  <organization-delete ref="organizationDel" @delete="orgOperate" />
</template>

<script setup>
  import organizationForm from '../components/organization-form.vue' //机构 添加、编辑
  import organizationDelete from '../components/organization-delete.vue' //机构 删除
  import { getTree, treeUp, treeDown } from '@/api/organization/organization'
  import { ref, onMounted } from 'vue'

  const editMouseIn = ref(false)
  const addMouseIn = ref(false)
  const deleteMouseIn = ref(false)
  const upMouseIn = ref(false)
  const downMouseIn = ref(false)

  // 树 数据
  const treeData = ref([])
  const getTreeData = (selectKeyArr) => {
    const param = {
      checkedId: '',
      isChecked: 'false',
      isOpen: 'true',
    }
    getTree(param).then((res) => {
      // console.log(res.result);
      const orgTree = res.result.map((e) => {
        e.key = e.id.toString()
        e.value = e.id
        e.title = e.name
        e.children = [] //创建子级
        return e
      })

      // console.log(orgTree);
      treeData.value = setTreeData(orgTree)
      emit('returnFirstId', treeData.value[0].key) //回传默认第一个组织机构id
      if (selectKeyArr) {
        // 上移下移后的展示点 重置操作按钮
        getSelectedNodes(selectKeyArr)
      }
    })
  }
  // 回传列表页 组织机构id
  const emit = defineEmits(['getSelectedNodes', 'resetList', 'getOrgId'])
  const returnOrgId = (e) => {
    emit('resetList', e)
  }

  // 表结构转化为树结构
  const setTreeData = (arr) => {
    // console.log(arr);
    // 删除所有的children,以防止多次调用
    arr.forEach(function (item) {
      delete item.children
      // console.log(item);
    })

    // console.log(arr);
    arr.sort((a, b) => {
      return a.sort - b.sort
    })
    let map = {} //构建map
    arr.forEach((i) => {
      map[i.id] = i //构建以id为键 当前数据为值
    })

    // console.log(map);
    let treeData = []
    arr.forEach((child) => {
      const mapItem = map[child.parentId] //判断当前数据的parentId是否存在map中
      if (mapItem) {
        // console.log(mapItem);
        //存在则表示当前数据不是最顶层的数据
        //注意： 这里的map中的数据是引用了arr的它的指向还是arr,当mapItem改变时arr也会改变，踩坑点
        ;(mapItem.children || (mapItem.children = [])).push(child) //这里判断mapItem中是否存在child
      } else {
        //不存在则是顶层数据
        child.top = true
        treeData.push(child)
      }
    })
    // treeData.filter(function(item,index){
    //   return treeData.indexOf(item) === index;  // 因为indexOf 只能查找到第一个
    // });

    // console.log(treeData[0])
    // console.log(setLast(treeData))

    // function setLast(obj) {
    //   if (obj.children && obj.children.length > 0) {
    //     setLast(obj.children[obj.children.length - 1])
    //   } else {
    //     obj.last = 1
    //   }
    // }
    treeData.forEach((item) => {
      addLast(item)
    })
    console.log(treeData)
    return treeData
  }

  const addLast = (obj) => {
    if (obj.children && obj.children.length > 0) {
      for (let i = 0; i < obj.children.length; i++) {
        const children = obj.children[i]
        if (i === obj.children.length - 1) {
          children.last = 1
        }
        addLast(children)
      }
    }
  }

  // 添加机构
  const orgAdd = (bool, nodeData) => {
    if (!bool) return
    organizationEdit.value.handleClick(nodeData, 'add', treeData)
    // console.log(nodeData.value)
    // const children = nodeData.children || []
    // children.push({
    //   title: 'new tree node',
    //   key: nodeData.key + '-' + (children.length + 1)
    // })
    // nodeData.children = children

    // treeData.value = [...treeData.value];
  }

  // 编辑机构
  const organizationEdit = ref(null)
  const orgEdit = (bool, nodeData) => {
    if (!bool) return
    organizationEdit.value.handleClick(nodeData, 'edit', treeData)
  }

  // 删除机构
  const organizationDel = ref(null)
  const orgDelete = (bool, nodeData) => {
    if (!bool) return
    organizationDel.value.handleClick(nodeData)
  }

  // const moveId = ref([])
  // 上移
  const orgUp = (bool, nodeData) => {
    if (!bool) return
    console.log('被上移节点id', nodeData.key)
    const param = {
      id: nodeData.key,
    }
    treeUp(param).then((res) => {
      console.log(res)
      // 移动后重新获取被选中的数据
      getTreeData([nodeData.key])
      // moveId.value.push(nodeData.key)
      // getSelectedNodes(moveId.value)
    })
  }
  // 下移
  const orgDown = (bool, nodeData) => {
    if (!bool) return
    console.log('被下移节点id', nodeData.key)
    const param = {
      id: nodeData.id,
    }
    treeDown(param).then((res) => {
      console.log(res)
      // 移动后重新获取被选中的数据
      getTreeData([nodeData.key])
      // moveId.value.push(nodeData.key)
      // getSelectedNodes([nodeData.key])
    })
  }

  // 操作结束后
  const orgOperate = (id) => {
    getTreeData()
    returnOrgId()
    // 同时，刷新列表页面
    emit('resetList', id)
    // emit('getOrgId', id)
  }

  // 获取点击节点
  const chooseOrg = ref('') //被选中的节点id
  const chooseOrgData = ref(null) //被选中的节点
  const getSelectedNodes = (e) => {
    console.log('获取被点击节点', e[0])
    chooseOrg.value = e[0]
    returnOrgId(chooseOrg.value) //回传刷新列表
    chooseOrgData.value = findChooseData(chooseOrg.value, treeData.value)[0]
    console.log('点击的节点信息', chooseOrgData.value)
  }

  // 查找选中节点
  const findChooseData = (id, list) => {
    // console.log(id)
    // console.log(list)
    var data = null
    ;(list || []).map((i) => {
      if (i.id == id) {
        data = [i]
      } else {
        const child = findChooseData(id, i.children)
        if (child) {
          data = child
        }
      }
    })
    return data
  }

  // mounted 调用接口
  onMounted(() => {
    getTreeData()
  })
</script>

<style lang="less" scoped>
  .org-tree {
    position: relative;
    margin-top: 16px;
    width: 96%;
    max-height: calc(100vh - 160px);
    background: #fbfbfc;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    overflow-x: auto;
    .org-tlt {
      position: sticky;
      z-index: 1;
      top: 0;
      left: 0;
      width: 100%;
      height: 40px;
      background: #f2f3f5;
      text-align: center;
      line-height: 40px;
      color: #1d2129;
      font-weight: 500;
      font-size: 14px;
    }
    .org-buttons {
      margin-bottom: 10px;
      position: sticky;
      z-index: 1;
      top: 40px;
      left: 0;
      border-top: 1px solid #e5e6eb;
      // padding: 12px;
      font-size: 12px;
      color: #c9cdd4;
      width: 100%;
      background-color: #f2f3f5;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .org-i {
        width: 25%;
      }
      .org-button {
        padding: 12px 9px;
        cursor: pointer;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
      }
      .org-button-active {
        color: #4e5969;
      }
      .org-mouse-active {
        color: #165dff;
      }
    }
    .org-line {
      height: 17px;
      width: 1px;
      background: #e5e5e5;
      position: absolute;
      right: 0;
    }
    .org-icons {
      min-width: 25px;
      max-width: 148px;
      float: right;
      position: absolute;
      right: 0;
      // top: 4px;
      height: 32px;
      background: #fbfbfc;
      display: flex;
      align-items: center;
      white-space: nowrap;
    }
  }

  :deep(.arco-tree-node-title) {
    white-space: nowrap;
  }

  :deep(.arco-tree-node-selected .arco-tree-node-title) {
    background-color: #f0f4ff;
    color: #165dff;
    width: max-content;
  }
  .org-icon {
    font-size: 18px;
    margin-right: 4px;
  }
  :deep(.arco-tree) {
    width: max-content;
  }
</style>
